package br.com.guarana.util;

import br.com.guarana.business.model.Parametro;
import br.com.guarana.business.service.ParametroService;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.tomcat.util.http.fileupload.DiskFileUpload;
import org.apache.tomcat.util.http.fileupload.FileItem;

/**
 *
 * @author 
 */
public class FileUpload extends HttpServlet {

    private static final long serialVersionUID = 1L;

    public FileUpload() {
    }

    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    @SuppressWarnings("unchecked")
    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //Caminho temporário no servidor
        //ServletContext sc = getServletConfig().getServletContext();
        //final String pastaUpload = new String(sc.getRealPath("/") + ".." + File.separator + "guaranafiles" + File.separator);
        //String nomeArquivo = request.getParameter("nomeArquivo");

        //busca diretório para gerar arquivo temporário
        Parametro parametroSistema = new ParametroService().buscaParametroDoSistema();
        String pastaUpload = parametroSistema.getDiretorioTemp();
        String nomeArquivo = request.getParameter("nomeImagem");

        try {
            System.out.println(pastaUpload + nomeArquivo);

            DiskFileUpload fu = new DiskFileUpload();
            // If file size exceeds, a FileUploadException will be thrown
            fu.setSizeMax(100000000);
            List fileItems = fu.parseRequest(request);

            Iterator itr = fileItems.iterator();
            while (itr.hasNext()) {
                FileItem fi = (FileItem) itr.next();

                //Check if not form field so as to only handle the file inputs
                //else condition handles the submit button input
                if (!fi.isFormField()) {
                    File fNew = new File(pastaUpload, nomeArquivo);
                    fi.write(fNew);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
